<template>
  <div class="content">
      <div style="padding-left:10px">
        <p class="tip">平台暂时只支持上传jpg，png，gif后缀格式的文件，每个文件大小控制在5M以内</p>
        <el-row :gutter="18">
          <el-col :span="12" style="display: flex">
            <el-upload class="upload-demo" ref="upload" multiple action="#" :before-upload="beforeUpload" :http-request="upload">
              <el-button class="el-icon-upload" size="small" type="primary">上传文件/图片</el-button>
            </el-upload>&nbsp;
            <el-button class="el-icon-delete" size="small" type="danger" @click="deletePic">批量删除</el-button>&nbsp;&nbsp;
            <p style="font-size: 14px;">移动到
              <el-select v-model="form.group_id" placeholder="请选择分组" style="width: 140px;" size="small" clearable @change="setAssocGroup">
                <el-option
                    v-for="item in group"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                </el-option>
              </el-select>
            </p>
          </el-col>
          <el-col :span="8" >
            <div class="files_type">
              <p class="title">文件类型：</p>
              <p :class="{'active': page_data.extension == ''}"  @click="toggle('')">全部</p>
              <p :class="{'active': page_data.extension == item}" v-for="(item, k) in extension"  @click="toggle(item)">{{ item }}</p>
            </div>
          </el-col>
        </el-row>
        <el-progress v-if="progress" :stroke-width="5" :percentage="progressPercent"></el-progress>
        <el-row style="margin-top:15px;">
          <el-col :span="24">
            <el-row>
              <div class="image-box">
                <div class="type">
                  <p :class="{'active': page_data.group_id === -1}" @click="toggleGroup(-1)">
                    <span class="name">全部</span></p>
                  <p :class="{'active': page_data.group_id === 0}" @click="toggleGroup(0)">
                    <span class="name">未分组</span>
                  </p>
                  <p :class="{'active': page_data.group_id == item.id}" v-for="(item, k) in group"  @click="toggleGroup(item.id)">
                    <span class="name">{{ item.name }}</span>
                    <span>
                      <i class="el-icon-delete" @click.stop="deleteGroup(item.id)"></i>
                      <i class="el-icon-edit" @click.stop="setGroupStatus(item)"></i>
                    </span>
                  </p>
                  <el-input v-model="form.group_name" placeholder="请输入名称" size="small" clearable v-if="add_group_status"></el-input>
                  <div class="add_btn_list">
                    <div class="add_btn " v-if="!add_group_status" @click.stop="setGroupStatus">
                      添加分组
                    </div>
                    <div class="add_btn" v-if="add_group_status" @click="addGroup">
                      保存&nbsp;
                    </div>
                    <div class="add_btn cancal" @click="add_group_status = false" v-if="add_group_status">
                      取消
                    </div>
                  </div>
                </div>
                <div class="box">
                  <div class="image-wrap"  v-for="(item,index) in list" :key="index" @click.stop="selection(item)">
<!--                    <label v-for="(v, k) in files" :key="k" v-if="files.length > 0">
                      <input type="checkbox" :checked="item.sign_url == v.sign_url">
                      <i :class="{'active':item.sign_url == v.sign_url}">✓</i>
                    </label>-->
                    <label>
                      <input type="checkbox" :checked="files_ids.indexOf(item.file_id) >= 0">
                      <i :class="{'active':files_ids.indexOf(item.file_id) >= 0}" class="checked_box">✓</i>
                    </label>
                    <div class="imgStyle">
                      <img :src="item.sign_url" /><br/>
                    </div>
                    <div class="size">尺寸(px)：{{ item.width }}*{{item.height}}</div>
                    <div class="group" v-if="item.group_id > 0">
                      分组：{{ item.group_name }}
                    </div>
                    <div class="name">{{ item.file_name }}</div>
                    <div class="cancal-group" v-if="page_data.group_id > 0">
                      <el-button type="primary" size="mini" @click="deleteFilesGroup(item.file_id)">取消分组</el-button>
                    </div>
                  </div>
                </div>
              </div>
            </el-row>
            <div class="pagination">
              <Page :total="page_data.total" :page.sync="page_data.page" :limit.sync="page_data.limit" @pagination="index" />
            </div>
          </el-col>
        </el-row>
      </div>

  </div>
</template>

<script>
import {fileList,removeFile,createFile,addGroup,groupList,assocGroup,deleteFilesGroup,deleteGroup} from '@/api/user/base'
import Page from '@/components/common/Page.vue'
import { confirm } from '@/utils/common'
export default {
  name:'fileList',
  components: {
    Page,
  },
  props: {
    limit: {
      type:Number,
      default: 0
    },
    fileList: {
      type: Array,
      default: []
    }
  },

  data() {
    return {
      files: this.fileList,
      files_ids: [],
      ids: [],
      list: [],
      extension: [],
      group: [],
      loading: false,
      progressPercent:0,
      progress:false,
      page_data: {
        limit: 14,
        page: 1,
        total: 0,
        extension: '',
        group_id: -1
      },
      form: {
        group_id: '',
        group_name: ''
      },
      add_group_status: false
    }
  },
  created() {
    this.files = []
    this.list = []
    this.index()
    this.getGroupList()
  },
  methods: {
    open(){
      this.files = []
      this.list = []
    },
    setAssocGroup() {
      if (this.files.length == 0) {
        this.form.group_id = ''
        this.$message({
          message: '请选择要移动的文件',
          type: 'error',
        })
        return false
      }
      let ids = this.files.map(item => { return item.id})
      assocGroup({ids: ids, group_id: this.form.group_id}).then(res => {
        this.form.group_id = ''
        if (res.code == 0) {
          this.index()
          this.$forceUpdate()
        }
      })
    },
    addGroup() {
      if (this.form.group_name == '') {
        this.$message({
          message: '请填写分组名称',
          type: 'error',
        })
        return false
      }
      if (this.form.group_name.length > 17) {
        this.$message({
          message: '分组名称不能多于17个字符',
          type: 'error',
        })
        return false
      }
      addGroup(this.form).then(res => {
        if (res.code == 0) {
          this.form.group_name = ''
          this.add_group_status = false
          this.getGroupList()
          this.index()
        }
      })
    },
    deleteGroup(id) {
      deleteGroup({id: id}).then(res => {
        if (res.code == 0) {
          this.form.group_id = ''
          this.form.group_name = ''
          this.getGroupList()
        }
      })
    },
    deleteFilesGroup(id) {
      deleteFilesGroup({file_id:id, group_id: this.page_data.group_id}).then(res => {
        if (res.code == 0) {
          this.index()
        }
      })
    },
    getGroupList() {
      groupList().then(res => {
        if (res.code == 0) {
          this.group = res.data
        }
      })
    },
    setGroupStatus(item) {
      if (typeof item.name != 'undefined') {
        this.form.group_name = item.name
        this.form.group_id = item.id
      } else {
        this.form.group_name = ''
        this.form.group_id = ''
      }
      this.add_group_status = true
    },
    toggleGroup(val) {
      this.form.group_id = ''
      this.page_data.group_id = val
      this.index()
    },
    toggle(val) {
      this.page_data.extension = val
      this.index()
    },
    index() {
      this.loading = true
      fileList(this.page_data).then(res => {
        this.list = res.data.list
        this.page_data.total = res.data.count
        this.extension = res.data.extension
        this.loading = false
        this.files = []
      })
    },
    selection(item) {
      let isExist = false
      if (this.files.length > 0) {
        for (let k in this.files) {
          if (this.files[k].id == item.file_id) {
            isExist = true
            this.files.splice(k, 1)
            this.files_ids.splice(k, 1)
          }
        }
        if (!isExist) {
          if (this.limit > 0 && this.files.length >= this.limit) {
            this.$message.error('图片数量不能超过'+this.limit+'张')
            return false
          }
          this.files_ids.push(item.file_id)
          this.files.push({
            id: item.file_id,
            sign_url: item.sign_url,
            file_url: item.file_url
          })
        }
      } else {
        if (this.limit > 0 && this.files.length >= this.limit) {
          this.$message.error('图片数量不能超过'+this.limit+'张，请取消后再选')
          return false
        }
        this.files_ids.push(item.file_id)
        this.files.push({
          id: item.file_id,
          sign_url: item.sign_url,
          file_url: item.file_url
        })
      }
      this.$emit('update:fileList', this.files)
    },
    deletePic(){
      confirm({content:'确定要操作吗'}).then(() => {
        removeFile({ids:this.files}).then(res => {
          //this.$message({message: res.msg, type: 'success'})
          this.index()
        })
      })
    },
    beforeUpload(item) {
      if(item.type.split('/')[0] === 'image') {
        let tempSize = item.size / 1024 / 1024
        if (tempSize > 5) {
          this.$message.error('图片尺寸不得大于5M！')
          return false
        }
      }
    },
    upload(item){
      let formdata = new FormData()
      let ali = new FormData()  //此处非常坑 阿里上传file属性必须要放到最后  所以只能赋值对象
      formdata.append('file', item.file)
      formdata.append('upload_config_id', '')
      let fileInfo = {
        file_name: item.file.name,
        file_size: item.file.size,
        file_type: item.file.type
      }

      const config = {
        onUploadProgress: progressEvent => {
          if (progressEvent.lengthComputable) {
            this.progress = true
            this.progressPercent = Number((progressEvent.loaded / progressEvent.total * 100).toFixed(2))
          }
        }
      }
      try {
        this.$axios.post('/api/base/file/upload', formdata,config).then(res => {
          if(res.data.code == 0){
            //if(!res.data.filestatus){
            if(res.data.data.type == 'qiniuyun'){
              formdata.append('token',res.data.data.token)
              formdata.append('key',res.data.data.key)
              this.$axios.post(res.data.data.serverurl, formdata,config).then(ret => {
                if(ret.data.key){
                  createFile({filepath:res.data.data.domain+'/'+ret.data.key}).then(res => {
                    this.progressPercent = 0
                    this.progress = false
                    this.index()
                  })
                }
              })
            }else if(res.data.data.type == 'ali'){
              ali.append('Signature',res.data.data.sign)
              ali.append('callback',res.data.data.callback)
              ali.append('OSSAccessKeyId',res.data.data.OSSAccessKeyId)
              ali.append('policy',res.data.data.policy)
              ali.append('key',res.data.data.key)
              ali.append('file', item.file)
              this.$axios.post(res.data.data.serverurl, ali,config).then(ret => {
                fileInfo.filepath = ret.data.data
                if(ret.data.code == 0){
                  createFile(fileInfo).then(res => {
                    this.progressPercent = 0
                    this.progress = false
                    this.index()
                  })
                }
              })
            } else {
              this.progressPercent = 0
              this.progress = false
              this.index()
            }
            /*}else{
              this.$message.error('文件已经存在')
            }*/
          }
        })
      }catch (error) {
        this.$message.error('上传失败')
      }finally {
        this.$refs.upload && this.$refs.upload.clearFiles()
      }
    },
  },
}
</script>

<style lang="scss" scoped >
.pagination {
  width:  100%;
  display: flex;
  justify-content: flex-end;
}
.tip {
  width: 90%;
  line-height: 30px;
  border: 0px solid #F57373;
  border-radius: 5px;
  text-align: center;
  margin: 0px auto 10px;
  font-size: 13px;
  color: #333;
  //background: #;
}
.files_type {
  width: 300px;
  line-height: 30px;
  display: flex;
  border: 0px solid #ccc;
  font-size: 14px;
  color:#333;
  p {
    margin-right: 10px;
    cursor: pointer;
  }
  .active {
    font-weight: bold;
    color: #00907F;
  }
}
.image-box {
  display: flex;
  .type {
    width: 200px;
    height: 100%;
    margin-right: 10px;
    border: 0px solid #ccc;
    cursor: pointer;
    overflow-y:auto;
    border-radius: 5px;
    background: #fff;
    padding-bottom: 20px;
    p {
      height: 28px;
      line-height: 28px;
      font-size: 14px;
      display: flex;
      justify-content: space-between;
      padding: 0 8px 0 0px;
      margin: 3px 0 3px 0;
      border: 0px solid #000;
      .name {
        margin:0;
        padding:0 5px 0 5px;
        height: 28px;
        line-height: 28px;
        width: 140px;
        border: 0px solid #ccc;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
      }
    }
    .el-icon-delete {
      color:#909399;
      margin-right: 3px;
    }
    .el-icon-edit {
      color:#909399;
    }
    .title {
      color:#303133;
      font-size: 14px;
    }
    .active {
      font-weight: bold;
      color: #00907F;
      // width: 100px;
      line-height: 30px;
      border: 0px solid #409EFF;
      border-radius: 3px;
      background: #F2F6FC;
    }
    .add_btn_list {
      display: flex;
      text-align:center;
      align-items: center;
      justify-content: space-between;
      margin: 0 5px;
      .add_btn {
        width: 50%;
        height: 28px;
        line-height: 28px;
        display: block;
        border: 0px solid #ff0000;
        border-radius: 3px;
        background: #409EFF;
        color:#fff;
        text-align:center;
        margin-top: 3px;
        font-size: 13px;
        p {
          font-size: 13px;
        }
        .el-icon-plus {
          font-size: 13px;
          margin:0;
        }
      }
      .cancal {
        width: 40%;
        height: 28px;
        line-height: 28px;
        display: block;
        border: 0px solid #ff0000;
        border-radius: 3px;
        background: #f56c6c;
        color:#fff;
        text-align:center;
        margin: 3px 0 0 3px;
      }
    }
  }
  .box {
    width: 85%;
    font-size: 14px;
    background: #fff;
    border-radius: 5px;
    .image-wrap {
      position: relative;
      display: inline-block;
      box-sizing: content-box;
      margin: 10px;
      vertical-align: top;
      border: 0px solid #ff0000;
      white-space: normal; /* 保留空白符序列，但是正常换行。*/
      word-break: break-all; /* 允许在单词内部任意位置换行 */
      cursor: pointer;
      &:hover {
        .icon-wrap {
          opacity: 1;
        }
      }
      .imgStyle {
        width:120px;
        height: 120px;
        border: 1px solid #d9d9d9;
        border-radius: 6px;
        overflow: hidden;
        display: flex;
        justify-content: center;
        align-items: center;
        img{
          height: 100%;
          margin: 0 auto;
          display: block;
          border-radius: 5px;
        }
      }

      .name {
        max-width: 120px;
        margin: 5px 0;
        color:#999;
        font-size: 13px;
      }
      .size {
        max-width: 120px;
        margin: 5px 0;
        color:#909399;
        font-size: 13px;
      }
      .group {
        max-width: 120px;
        margin: 5px 0;
        color:#999;
        font-size: 13px;
      }
      .cancal-group {
        max-width: 120px;
        margin: 3px 0;
      }
      .icon-wrap {
        position: absolute;
        left: 0;
        border-radius: 6px;
        width: 122px;
        height: 122px;
        cursor: default;
        text-align: center;
        line-height: 100px;
        color: #fff;
        opacity: 0;
        font-size: 20px;
        background-color: rgba(0, 0, 0, .7);
        transition: opacity .3s;
        .el-icon-zoom-in {
          cursor: pointer;
          margin-right: 8px;
        }
        .el-icon-delete {
          cursor: pointer;
        }
      }
    }
  }
}


label {
  font-size: 25px;
  cursor: pointer;
  position: absolute;
  top: -2px;
  right: 2px;
  z-index: 150;
}

label i {
  font-size: 15px;
  font-style: normal;
  display: inline-block;
  width: 18px;
  height: 18px;
  text-align: center;
  line-height: 18px;
  color: #fff;
  vertical-align: middle;
  margin: -3px 0px 1px 0px;
  border-radius: 25px;
}
.checked_box {
  background: #ccc;
  color:#fff;
}
.active {
  background: #409EFF;
  color: #FFF;
}

input[type="checkbox"],
input[type="radio"] {
  display: none;
  outline: none;
}

input[type="radio"]+i {
  border-radius: 7px;
}
/*
input[type="checkbox"]:checked+i,
input[type="radio"]:checked+i {
  background: #409EFF;
  color: #FFF;
}*/
@import '@/assets/scss/common.scss'
</style>